/******************************************************************************************
 * Import
 ******************************************************************************************/

// module
import Taro, { Component } from '@tarojs/taro'
import { Input, Switch } from '@tarojs/components'
// 引入省市区组件
import AreaSelect from '../../../project/untils/area_picker'
import area from '../../../project/untils/area'

// project
import { CPage, CContent, CHeader, CFooter, CFloat, CAround, CBetween, CCenter, CRow, CWrap, CLine, CHand, CItemX, CItemY, CText, CLabel, CSvg, CImage, CButton, CColumn } from '../../../library/comp';
import { Base64, Gen, Time, Zip, Session, Storage, Toast, Loading, Modal, ActionSheet } from '../../../library/func';
import Icon from '../../../project/style/icon';
import Http from '../../../project/func/http/http'

/******************************************************************************************
 * Export Class
 ******************************************************************************************/

export default class AddressAdd extends Component {

	/*------------------------------------------------------------------------------------
	 * 初始化
	 *-----------------------------------------------------------------------------------*/
	constructor(props) {
		super(props);

		/**
		 * state
		 */
		this.state = {
			background: '#f60',
			status: 'success',
			// 是否显示选择省市区组件
			show: false,
			// 用户添加地址
			set_name: '',
			set_mobile: '',
			set_address: '',
			is_defaulted: 0,
			set_province: '',
			set_city: '',
			set_district: '',
			// 进页面获取的省市区
			// 省
			province: '选择省份',
			// 市
			city: '选择城市',
			// 区
			area: '选择地区',
			index: [0, 0, 0],

			// 判断来源，正常添加还是从订单提交添加
            type: 0
		}
	}

	/*------------------------------------------------------------------------------------
	 * 生命周期
	 *-----------------------------------------------------------------------------------*/
	// willmount
	componentWillMount() {
		// 改变type
        this.setState({
            type: this.$router.params.type
        })
    }
	// didMount
	componentDidMount() {
		Taro.getLocation({
            type: 'gcj02',
            success:(res)=> {
                // console.log('经度====',res.longitude)
                // console.log('纬度====',res.latitude)
               // 调用高德地图逆地理编码api
                Taro.request({
                    url:'https://restapi.amap.com/v3/geocode/regeo?key='+'4b984fdef9356e66e5d70e0f3e45730c&location=' + res.longitude + ',' +  res.latitude,
                    success:(res)=> {
                        this.setState({
							province: res.data.regeocode.addressComponent.province,
							city: res.data.regeocode.addressComponent.city,
							area: res.data.regeocode.addressComponent.district,
                            // index1: area.getValue(res.data.regeocode.addressComponent.province, res.data.regeocode.addressComponent.city, res.data.regeocode.addressComponent.district)
                        },()=>{
                            // console.log('省份====',this.state.province)
                            // console.log('市====',this.state.city)
                            // console.log('区====',this.state.area)
                            // console.log('index111 is', that.state.index1)
                        })
                        this.setState({
                            index: [1, 1, 1]
                        })
                    },
                   
                })
               
            }
        })
	}
	
	/*------------------------------------------------------------------------------------
	 * 事件处理
	 *-----------------------------------------------------------------------------------*/
	//navigateBack
	onNavigateBack = (e) => {
		wx.navigateBack({
			delta: 1
		})
	}

	// 改变地址信息
    handleChange(type, e) {
        this.setState({
			set_province: this.state.province,
			set_city: this.state.city,
			set_district: this.state.area,
        })
        
        if (type == 'name') {
            this.setState({
				set_name: e.detail.value,
            },()=>{
				// console.log('123=====',this.state.set_name)
			})
        }
        if (type == 'mobile') {
            this.setState({
				set_mobile: e.detail.value,
            })
        }
        if (type == 'address') {
            this.setState({
				set_address: e.detail.value,
            })
        }
        if (type == 'defaulted' && e.detail.value == true) {
            this.setState({
				is_defaulted: 1,
            })
        } else {
            this.setState({
				is_defaulted: 0,
            })
        }

    }
	
	// 用户添加地址
	addAddress = ()=>{

		var post_field = [
			"set_name",
			"set_mobile",
			"set_address",
			"is_defaulted",
			"set_province",
			"set_city",
			"set_district"
		];

		for(var item of post_field){
			if(item != "is_defaulted"){
				if(this.state[item] == ""){
					Toast.text("信息需填写完整");
					return;
				}
			}
		}

		Http.post({
			url:'take/logic/add.php',
			data:{
				set_name: this.state.set_name,
				set_mobile: this.state.set_mobile,
				set_address: this.state.set_address,
				is_defaulted: this.state.is_defaulted,
				set_province: this.state.set_province,
				set_city: this.state.set_city,
				set_district: this.state.set_district
			},
			success:(data) => {
				Toast.success('添加成功！')
				// 如从订单提交页面跳转的添加地址，添加完后跳回订单提交页面
                if(this.state.type == 1) {
                    setTimeout(function () {
                        wx.navigateTo({
                            url: '/screen/order/submit',
                        })
                    }, 1500)
                }
                // 如正常添加地址，添加完后跳到地址列表
                if(this.state.type ==0) {
					setTimeout( () => {
                        this.onNavigateBack();
					}, 1500)
                }
				// setTimeout(function () {
				// 	wx.navigateTo({
				// 		url: '/screen/user/address/list',
				// 	})
				// }, 1500)
			}
		})
	}

	// 设为默认地址开关change事件
	default = (e) => {
		// console.log(e.detail.value)
	}

	// 显示省市区选择组件
	onshow(e){
        this.setState({
            province: this.state.province,
            city: this.state.city,
            area: this.state.area,
            show: true,
        })
    }

	// 改变地址点击确定
	onChange(data) {
        this.setState({
			province : data.province1,
			city: data.city1,
			area: data.area1,
			show: data.show
        })
	}

	// 取消省市区选择组件
	cancel(data){
        this.setState({
            show: data.show
        })
    }
	

	/*------------------------------------------------------------------------------------
	 * 自定义方法
	 *-----------------------------------------------------------------------------------*/
	config = {
        navigationBarTitleText: '添加地址',
        navigationBarBackgroundColor: '#dd2f3c',
        navigationBarTextStyle: '#fff'
    }


	/*------------------------------------------------------------------------------------
	 * 渲染
	 *-----------------------------------------------------------------------------------*/
	render () {
		return (
			<CPage>
				<CContent bg='#f5f5f5' h='1600'>
					
					{/* 用户添加收货地址 */}
					<CColumn bg='#fff' ra='20' ma='30' px='30' pb='30'>

						{/* 姓名 */}
						<CLine style='border-bottom:2rpx solid #f5f5f5' h='100'>
							<Input style="font-size:28rpx" name='name' type='text' placeholder='收货人姓名' value={this.state.set_name} placeholderStyle='color:#979797' onInput={this.handleChange.bind(this, 'name')} />
						</CLine>

						{/* 手机号 */}
						<CLine style='border-bottom:2rpx solid #f5f5f5' h='100'>
							<Input style="font-size:28rpx" name='name' type='number' placeholder='联系人电话' maxLength='11' placeholderStyle='color:#979797' value={this.state.set_mobile} onInput={this.handleChange.bind(this, 'mobile')} />
						</CLine>

						{/* 省市区 */}
						<CLine style='border-bottom:2rpx solid #f5f5f5' h='100' onClick={this.onshow}>
							<CBetween>
								<CHand>
									<CText color='#535353' size='28'>所在地区：</CText>
									<CHand color='#535353' size='28'>{this.state.province}</CHand>
									<CHand color='#535353' size='28' pl='10'>{this.state.city}</CHand>
									<CHand color='#535353' size='28' pl='10'>{this.state.area}</CHand>
								</CHand>
									
								<CHand>
									<CSvg icon={Icon.right} w='30' h='30'></CSvg>
								</CHand>
							</CBetween>
						</CLine>

						{/* 详细地址 */}
						<CLine style='border-bottom:2rpx solid #f5f5f5' h='100'>
							<Input style="font-size:28rpx" name='name' type='text' placeholder='详细地址' placeholderStyle='color:#979797' value={this.state.set_address} onInput={this.handleChange.bind(this, 'address')} />
						</CLine>

						{/* 设为默认地址 */}
						<CLine h='120'>
							<CBetween>
								<CHand>
									<CText color='#535353' size='28'>设为默认地址</CText>
								</CHand>
								<CHand>
									<Switch
										color='#de001c'
										onChange={this.handleChange.bind(this, 'defaulted')}
									/>
								</CHand>
							</CBetween>
						</CLine>

					</CColumn>

					{/* 保存按钮 */}
					<CButton bg='#de001c' size='28' ma='30' ra='16' h='80' y='center' color='#fff' onClick={this.addAddress}>保存</CButton>

					{/* 省市区组件 */}
					{this.state.show == true && 
						<AreaSelect index={this.state.index} onChange={this.onChange} onCancel={this.cancel} province={this.state.province} city={this.state.city} area={this.state.area} ></AreaSelect>
					}

				</CContent>
			</CPage>
		)
	}
}


